<template>
  <div class="person-container">
    <div class="person-header">
      <div class="person-setting" @click="showSettingPopup(true)" />
      <van-action-sheet
        v-model:show="showSetting"
        :actions="[
          {
            name: '账号信息',
          },
        ]"
        cancel-text="退出登录"
        close-on-click-action
        @cancel="onLoginOut"
        @select="onSelect"
      />
      <van-image
        round
        width="5rem"
        height="5rem"
        fit="cover"
        :src="avatarImg"
      />
      <div>
        <van-badge color="#fff">
          <span style="font-size: 22px">{{ name }}</span>
          <template #content>
            <van-image :src="girlIcon" width="1rem" fit="cover"></van-image>
          </template>
        </van-badge>
      </div>

      <div style="font-size: 14px">
        <span style="margin-right: 10px">{{ ageChinese }}</span>
        <span>{{ userStore.userData.birthplace }}</span>
      </div>
      <div>
        <van-row :gutter="10">
          <van-col :span="12">
            任务 {{ userStore.userData.taskCount }} 个
          </van-col>
          <van-col :span="12">
            书籍 {{ userStore.userData.bookCount }} 本</van-col
          >
          <!-- <van-col :span="8">复习 X 次</van-col> -->
        </van-row>
      </div>
    </div>
    <div class="person-content">
      <div class="balance">
        <div class="balance-icon">
          <van-image fit="cover" width="4rem" :src="Pig" />
        </div>
        <div class="balance-content">
          <span class="balance-title">余额：</span>
          <span class="balance-big"
            >¥{{ Math.floor(Number(balance) / 100) }}</span
          >.
          <span class="balance-small">
            {{ (Number(balance) / 100).toString().split(".")[1] }}
          </span>
        </div>
      </div>

      <div class="cell-list">
        <div
          class="cell-item"
          @click="
            () => {
              router.push({
                name: 'reviewList',
              });
            }
          "
        >
          <van-image
            class="cell-icon"
            :src="cellIcon"
            fit="cover"
            width="1.5rem"
          ></van-image>
          <div class="cell-text">我要复习</div>
        </div>
        <div class="cell-item" @click="randomReviewOnShow">
          <van-image
            class="cell-icon"
            :src="cellIcon"
            fit="cover"
            width="1.5rem"
          ></van-image>
          <div class="cell-text">每日一题</div>
        </div>
        <div class="cell-item">
          <van-image
            class="cell-icon"
            :src="cellIcon"
            fit="cover"
            width="1.5rem"
          ></van-image>
          <div class="cell-text">我的读书币</div>
        </div>
      </div>
    </div>

    <!-- 每日一题 -->
    <van-dialog
      class="review-dialog"
      v-model:show="randomReviewDialog"
      show-cancel-button
      cancelButtonText="关闭"
      @cancel="randomOnCancel"
      :showConfirmButton="false"
    >
      <div class="review-dialog-body">
        <div class="header">
          <div class="header-left">
            <div class="header-left_num">{{ randomInfo.reviewCount || 0 }}</div>
            <div class="header-left_text">次数</div>
          </div>
          <div class="header-right">
            <div class="header-right_time">
              <span style="font-weight: 600">{{
                randomInfo.reviewTime
                  ? dayjs(randomInfo.reviewTime).format("MM.DD")
                  : "第一次"
              }}</span>

              <span style="margin-left: 10px; font-size: 16px">
                {{
                  randomInfo.reviewTime
                    ? dayjs(randomInfo.reviewTime).format("YYYY")
                    : "复习哦"
                }}
              </span>
            </div>
            <div class="header-right_text">上次复习</div>
          </div>
        </div>
        <div class="random-body">
          <div class="review-title">{{ randomInfo.title || "题目丢失啦" }}</div>
          <div class="random-time">
            <div>{{ dayjs(randomInfo.time).format("HH:MM") }}</div>
            <div>{{ dayjs(randomInfo.time).format("YYYY-MM-DD") }}</div>
          </div>
        </div>

        <div class="review-btn" @click="randomOnConfirm">复习</div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { computed, reactive, ref, toRefs } from "vue";
import { useUserStore } from "../../stores";
import { getUserBalance } from "../../service/user";
import { randomReview, createReview } from "../../service/review";
import boyIcon from "@/assets/images/boy.png";
import girlIcon from "@/assets/images/girl.png";
import avatarImg from "@/assets/images/avatar.png";
import { showToast, showSuccessToast } from "vant";
import Pig from "@/assets/images/pig.png";
import cellIcon from "@/assets/images/feedback.png";
import { useRoute, useRouter } from "vue-router";
import { treeData } from "../../../../childHabit-manage/src/views/demo/tree/data";
import dayjs from "dayjs";
import "./index.less";

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

const { avatar, name, birthday } = userStore.userData;

const balance = ref(0);

const ageChinese = computed(() => {
  return calculateAgeInChinese(dayjs(birthday).format("YYYY-MM"));
});

const calculateAgeInChinese = (birthYearMonth) => {
  const [birthYear, birthMonth] = birthYearMonth.split("-").map(Number);
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1; // JavaScript months are 0-indexed
  let ageInMonths =
    (currentYear - birthYear) * 12 + (currentMonth - birthMonth);
  let ageInHalfYears = Math.floor(ageInMonths / 6) / 2;
  let ageInChinese = "";

  const chineseNumerals = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
    "十",
  ];
  let fullYears = Math.floor(ageInHalfYears);

  if (fullYears >= 10) {
    if (fullYears < 20) {
      ageInChinese =
        "十" + (fullYears % 10 === 0 ? "" : chineseNumerals[fullYears % 10]);
    } else {
      ageInChinese =
        chineseNumerals[Math.floor(fullYears / 10)] +
        "十" +
        (fullYears % 10 === 0 ? "" : chineseNumerals[fullYears % 10]);
    }
  } else {
    for (const digit of fullYears.toString()) {
      ageInChinese += chineseNumerals[parseInt(digit, 10)];
    }
  }

  if (ageInHalfYears % 1 !== 0) {
    ageInChinese += "岁半";
  } else {
    ageInChinese += "岁";
  }
  return ageInChinese;
};
const getBalanceInfo = async () => {
  const { data } = await getUserBalance();
  balance.value = data.balance;
};

const showSetting = ref(false);
const showSettingPopup = (bool) => {
  showSetting.value = bool;
};

const randomReviewDialog = ref(false);

const randomInfo = ref({});

const randomReviewOnShow = async () => {
  const { data } = await randomReview();
  randomInfo.value = data;
  randomReviewDialog.value = true;
};

const randomOnConfirm = async () => {
  const { data } = await createReview({
    time: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    cUserTaskId: randomInfo.value.id,
    isEnd: 0,
  });

  if (data == 1) {
    showSuccessToast({
      message: "已加入复习列表",
    });
    randomReviewDialog.value = false;
  }
};

const randomOnCancel = () => {
  randomReviewDialog.value = false;
};

const onSelect = (item) => {
  if (item.name == "账号信息") {
    router.push({
      name: "personagePerfect",
    });
  }
};
const onLoginOut = () => {};

getBalanceInfo();
</script>

<style scoped lang="less">
.person-container {
  display: flex;
  flex-direction: column;
  padding: 0;

  .person-header {
    height: 200px;
    background: #78669c;
    width: 100%;
    padding: 16px;
    text-align: center;
    color: #fff;
  }

  .person-setting {
    display: inline-block;
    width: 26px; /* 图标的宽度 */
    height: 26px; /* 图标的高度 */
    background-image: url("@/assets/images/setting-fill.svg");
    background-size: contain;
    background-repeat: no-repeat;
    top: 20px;
    right: 20px;
    position: absolute;
  }
  .person-content {
    flex: 1;
    .balance {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      margin: 20px;
      background: #78669c;
      opacity: 0.65;
      border-radius: 8px;

      .balance-icon {
      }
      .balance-content {
        color: #f2b275;
        display: flex;
        align-items: baseline;
        font-weight: 600;

        .balance-title {
          font-weight: 600;
        }

        .balance-big {
          font-size: 24px;
          font-weight: 600;
        }
        .balance-small {
          font-size: 18px;
          font-weight: 600;
        }
      }
    }

    .cell-list {
      margin: 22px;
      .cell-item {
        border-radius: 2px;
        border: 2px solid #7c63a0;
        display: flex;
        align-items: center;
        padding: 9px 11px;
        margin-bottom: 16px;

        .cell-icon {
          transform: rotate(90deg);
        }

        .cell-text {
          margin-left: 10px;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
